<style>
	.webuploader-pick {
		background: unset;
		padding: unset;
	}
</style>
<template>
	<div>
		<el-row class="webUploader">
			<el-col :span="24" class="mb20" :style="{ display: 'flex' }">
				<el-button class="selectFile" :disabled="disabled" type="primary" size="mini" ref="selectFile">
					选择文件
				</el-button>
			</el-col>
			<el-col :span="24" v-if="value && value.length > 0">
				<el-table :data="value" :disabled="disabled" size="mini">
					<el-table-column label="文件名" align="left" key="fileName" prop="fileName"
						:show-overflow-tooltip="true" />
					<el-table-column label="大小" align="center" key="fileSize" prop="fileSize"
						:show-overflow-tooltip="true" />
					<el-table-column label="进度" align="center" key="fileProgress" prop="fileProgress">
						<template slot-scope="scope">
							<el-progress :text-inside="true" :stroke-width="16"
								:percentage="scope.row.fileProgress"></el-progress>
						</template>
					</el-table-column>
					<el-table-column label="状态" align="center" key="fileStatus" prop="fileStatus"
						:show-overflow-tooltip="true" />
					<el-table-column label="操作" align="center" class-name="small-padding fixed-width">
						<template slot-scope="scope">
							<el-button size="mini" type="text" icon="el-icon-video-pause" @click="stop(scope.row.file)"
								:disabled="scope.row.fileStatus === '上传成功'">暂停</el-button>
							<el-button size="mini" type="text" icon="el-icon-delete" :disabled="disabled"
								@click="remove(scope.row, scope.$index)">移除</el-button>

						</template>
					</el-table-column>
				</el-table>
			</el-col>
		</el-row>
	</div>
</template>

<script>
	import WebUploader from "webuploader";
	import "webuploader/dist/webuploader.css";
	let APPKEY = '5da5441f62e48aedc7a3853ffc75c2db';
	let PRODID = 'gf';
	let UPLOAD_ACTION = '/upload';
	let VIEW_ACTION = '/view';
	let REMOVE_ACTION = '/remove';
	let chunkSize = 5120000
	export default {
		name: "uploaderList",
		components: {},
		props: {
			accept: {
				type: [String, Object],
				default: 'text'
			},
			// 上传地址
			url: {
				type: String,
				default: "sliceFile/uploadSliceFile"
				//default: "https://www.weifeibangbang.com/sliceFile/uploadSliceFile"
			},
			// 上传最大数量 默认为100
			fileNumLimit: {
				type: Number,
				default: 100
			},
			// 大小限制 默认2M
			fileSingleSizeLimit: {
				type: Number,
				default: 5120000
			},
			fileType: {
				type: String,
				default: "knowledge"
			},
			// 上传时传给后端的参数，一般为token，key等
			formData: {
				type: Object,
				default: () => {
					return {
						appKey: APPKEY,
						prodID: PRODID
					};
				}
			},
			// 生成formData中文件的key，下面只是个例子，具体哪种形式和后端商议
			keyGenerator: {
				type: Function,
				default: () => `${new Date().getTime()}`
			},
			multiple: {
				type: Boolean,
				default: false
			},
			// 上传按钮ID
			uploadButton: {
				type: String,
				default: ""
			},
			value: {
				type: Array,
				default: () => []
			},
			disabled: {
				type: Boolean,
				default: () => false
			}
		},
		data() {
			return {
				uploader: null
			};
		},
		watch: {
			disabled(newVal) {
				if (newVal) {
					this.uploader.destroy();
					return false;
				}
				this.initWebUpload();
			}
		},
		mounted() {
			if (!this.disabled) {
				this.initWebUpload();
			}
		},
		methods: {

			randomChar: function(l) {
				var x = "0123456789qwertyuioplkjhgfdsazxcvbnm";
				var tmp = "";
				var timestamp = new Date().getTime();
				for (var i = 0; i < l; i++) {
					tmp += x.charAt(Math.ceil(Math.random() * 100000000) % x.length);
				}
				return timestamp + tmp;
			},

			initWebUpload() {
				if (this.uploader) {
					this.uploader.destroy();
				}
				this.formData.businessCode = this.randomChar(19)
				const uploader = (this.uploader = WebUploader.create({
					auto: false, // 选完文件后，是否自动上传
					// swf: '/static/lib/webuploader/Uploader.swf',  // swf文件路径
					server: this.baseURL + this.url, // 文件接收服务端
					pick: {
						id: this.$refs.selectFile.$el, // 选择文件的按钮
						multiple: this.multiple // 是否多文件上传 默认false
					},
					accept: this.getAccept(this.accept), // 允许选择文件格式。
					threads: 3,
					fileNumLimit: this.fileNumLimit, // 限制上传个数
					//fileSingleSizeLimit: this.fileSingleSizeLimit, // 限制单个上传图片的大小
					formData: this.formData, // 上传所需参数
					chunked: true, //分片上传
					chunkSize: chunkSize, //分片大小
					duplicate: true // 重复上传
				}));
				const fun = [
					"fileQueued",
					"uploadStart",
					"uploadProgress",
					"uploadSuccess",
					"error"
				];
				for (const item of fun) {
					uploader.on(item, this[item]);
				}
				return uploader;
			},
			// 当有文件被添加进队列的时候，添加到页面预览
			fileQueued(file) {
				const {
					name,
					size,
					id
				} = file;
				const obj = {
					id,
					fileName: name,
					fileSize: WebUploader.Base.formatSize(size),
					fileProgress: 0,
					fileStatus: "待上传",
					file
				};
				this.value.push(obj);
			},
			// 在这里可以准备好formData的数据
			uploadStart() {
				this.uploader.options.formData.guid = this.keyGenerator();
			},
			// 文件上传过程中创建进度条实时显示。
			uploadProgress(file, percentage) {
				const fileObj = this.value.find(obj => file.id == obj.id);
				fileObj.fileStatus = "上传中";
				fileObj.fileProgress = parseInt(percentage * 100);
				fileObj.file = file;
			},
			// 文件上传成功
			async uploadSuccess(file, res) {
				let that = this
				let chunks = Math.ceil(file.size / chunkSize)

				that.ajax({
					url: '/sliceFile/mergeSliceFile',
					data: JSON.stringify({
						chunks: chunks,
						guid: that.uploader.options.formData.guid,
						name: file.name,
					}),
					contentType: 'application/json',
					dataType: 'json',
					method: 'POST',
					success: function(result) {
						that.$emit('success', result.data)
					},
				})
			},
			error(type) { //报错信息
				let errorMessage = "";
				if (type === "F_EXCEED_SIZE") {
					errorMessage = `文件大小不能超过${this.fileSingleSizeLimit /
	          (1024 * 1000)}M`;
				} else if (type === "Q_EXCEED_NUM_LIMIT") {
					errorMessage = "文件上传已达到最大上限数";
				} else {
					errorMessage = `上传出错！请检查后重新上传！错误代码${type}`;
				}
				console.error(errorMessage);
			},
			// 开始
			resume(file) {
				if (this.value.length == 0) {
					return this.$message({
						message: '请上传文件',
						type: 'warning'
					});
				}
				this.uploader.upload(this.value[0].file);
			},
			// 暂停
			stop(file) {
				file.fileStatus = "暂停中";
				this.uploader.stop(file);
			},
			// 移除
			async remove(row, idx) {
				const {
					fileId,
					file
				} = row;
				try {
					if (fileId) await delFileApi(fileId);
					this.value.splice(idx, 1);
					if (file) {
						// 取消并中断文件上传
						this.uploader.cancelFile(file);
						// 在队列中移除文件
						this.uploader.removeFile(file, true);
					}
					this.$emit("input", this.value);
				} catch (error) {}
			},

			//上传文件格式
			getAccept(accept) {
				console.log(accept)
				switch (accept) {
					case "pdf":
						return {
							title: "Texts",
							exteensions: "pdf",
							mimeTypes: ".pdf"
						};
					case "text":
						return {
							title: "Texts",
							exteensions: "doc,docx,xls,xlsx,ppt,pptx,pdf,txt",
							mimeTypes: ".doc,docx,.xls,.xlsx,.ppt,.pptx,.pdf,.txt"
						};
					case "video":
						return {
							title: "Videos",
							exteensions: "mp4",
							mimeTypes: ".mp4"
						};
					case "image":
						return {
							title: "Images",
								exteensions: "gif,jpg,jpeg,bmp,png,tif",
							mimeTypes: ".gif,.jpg,.jpeg,.bmp,.png,.tif"
						};
					default:
						return accept;
				}
			},
			submitFile() {
				this.uploader.upload();
			}
		}
	};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

</style>